<style lang="scss" scoped>
@import '../../css/resource.scss';
.el-radio{padding: 10px 0 0 0;display: block}
.el-radio+.el-radio {margin-left: 0;margin-top: 10px;}
.el-form-item{margin-bottom: 30px;}
.main-content{background: #fff;padding: 40px 0 80px 0;}
.choose-btn{position: absolute;bottom: -12px;color: $mco;cursor: pointer;}
.cover-box{height: 300px;width: 400px;border-radius: 5px;border: 1px solid #ccc;text-align: center;line-height: 300px;font-size: 30px;color: #999;}
.cover-box img{width: 100%;height: 100%;}
.avatar-word{color: $mc3;margin-top: 10px;}
.avatar-uploader-icon1 {
    font-size: 16px;
    color: #8c939d;
    width: 38px;
    height: 38px;
    line-height: 38px;
    text-align: center;
    border:1px solid #d8dce5;
    border-radius: 4px;
    margin-left: 8px;
    cursor: pointer;
    &:hover{border-color: #bbb}
}

.input-dialog{padding-left: 40px;}
.word-dialog-tap{padding: 8px 0 0 40px;}
.dialog-btn-left{width: 150px;margin: 0 10px 0 -4px;}
.dialog-btn-right{width: 150px;background: $mco;}

.dialog-btn-upload{width: 150px;background: #eee;color: #333;border:none;}

.dialog-big-body{ margin-top: -20px;}
.dialog-big-body-head{padding: 12px 20px;background: #fcfdff;border-bottom: 1px solid #eee;position: relative;}
.student-name{margin-right: 40px;}
.student-box{height: 24px;}
.student-box span{cursor: pointer;}

.input-dialog-big{position: absolute;left: 48px;top: 9px;width: 560px;height: 24px;outline: none;border:none;background: #fcfdff;}
.input-search-left{position: absolute;left: 20px;top: 9px;font-size: 26px;color: #ccc;}
.input-search-right{position: absolute;right: 20px;top: 9px;font-size: 26px;color: #ccc;}
.add-resource .el-form-item.is-success .el-input__inner{border-color:#d8dce5;}
.add-resource-abel-input .el-input{width: 100%;}
</style>
<style>

.resource-dialog .el-dialog__header {
    padding:40px 0 30px !important;
}

.dialog-big-body-main {
    display: flex;
    justify-content: space-between;
}

.resource-dialog-header {
    display: flex;
    justify-content: space-between;
    align-items:center;
    margin-bottom:10px;
}

.resource-dialog-header > span {
    color:#7485B1;
    font-size:14px;
}

.resource-dialog-header .el-input {
    width:160px;
    height:40px;
    border-radius:2px;
}

.dialog-big-body-main .dialog-big-cont-l{
    width:280px;

    border-radius:2px;
    border:1px solid rgba(225,231,235,1);
}


.dialog-big-body-title {
    width:100%;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size:14px;
    color:#3A3A63;
}

.dialog-big-body-content {
    padding:16px 0;
    border-top:1px solid rgba(225,231,235,1);
}

.dialog-big-body-content .resource-tree {
    width:100%;
    height:235px;
    max-height: 235px;
    overflow-y: auto;
    color:#7485B1;
}

.dialog-big-cont-r {
    width:344px;
    height: 318px;
    border:1px solid rgba(225,231,235,1);
    border-bottom:none;
}
.dialog-big-cont-r .el-table td,.el-table th {
    border-bottom: 1px solid #e6ebf5;
}

.dialog-big-cont-r .el-table tr {
    background-color: #fff;
    display: table;
    width:100%;
    table-layout: fixed;
}

.dialog-big-cont-r .el-table tr:hover td {
    background-color: #f5f7fa;
}

.dialog-big-cont-r .el-table tbody{
    display: block;
    width: 100%;
    height: 268px;
    overflow-y: auto;
}


.dialog-big-cont-r .el-table .checkbox {
    display: inline-block;
    position: relative;
    border: 1px solid #dcdfe6;
    border-radius: 2px;
    box-sizing: border-box;
    width: 14px;
    height: 14px;
    background-color: #fff;
    z-index: 1;
    transition: border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46);
    margin:0 14px 0 14px;
}

.dialog-big-cont-r .el-table .checkbox:after {
    box-sizing: content-box;
    content: "";
    border: 1px solid #fff;
    border-left: 0;
    border-top: 0;
    height: 7px;
    left: 4px;
    position: absolute;
    top: 1px;
    transform: rotate(45deg) scaleY(0);
    width: 3px;
    transition: transform .15s ease-in .05s;
    transform-origin: center;
}

.dialog-big-cont-r .el-table .checkbox:hover {
    border-color: #409eff;
}

.dialog-big-cont-r .el-table input:checked + .checkbox{
    background-color: #409eff;
    border-color: #409eff;
}


.dialog-big-cont-r .el-table input:checked + .checkbox:after{
    transform: rotate(45deg) scaleY(1);
}

.clip-img {
    height: 300px;
    width: 400px;
}

</style>
<template>
    <section class="add-resource">
        <div class="main-content">
            <el-form  :model="form" :rules="rules" ref="form" label-width="180px">
                <el-form-item label="资源名称" prop="resName" >
                    <el-input class="input" v-model="form.resName" placeholder="请输入资源名称" maxlength="50"></el-input>
                </el-form-item>

                <el-form-item label="资源类型" prop="resTypeID" :rules="[{ required: true, message: '请选择类型', trigger: 'change' }]">
                  <el-cascader
                      :options="departmentList"
                      :props="resTypeIDprops"
                      v-model="form.resTypeID"
                      :show-all-levels="false"
                    ></el-cascader>
                </el-form-item>

                <!-- resCateID -->
                <!-- departmentList -->
                <el-form-item label="上传封面"  prop="resCover">
                    <div class="clip-img">
                        <clip-img
                            :fixedBox = 'true'
                            :canScale = 'true'
                            :src="src"
                            @updateImg="getUploadImg"
                        ></clip-img>
                        <div class="avatar-word">建议尺寸340*456px或3:4，JPG/PNG格式，图片小于5M</div>
                    </div>
                </el-form-item>


                <el-form-item label="备注" prop="resDesc" >
                    <el-input class="input" v-model="form.resDesc" placeholder="点击输入备注供自己查看"></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="22">
                        <el-form-item label="资源简介" prop="resAbstract" >
                            <editor :content="inputContent" v-model="form.resAbstract"></editor>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-button class="dialog-btn-right" type="primary" @click="submitForm('form')">保存</el-button>
                    <!-- <el-button class="dialog-btn-upload" type="primary" @click="submitForm('form',1)">保存并上传素材</el-button> -->
                </el-form-item>
            </el-form>
        </div>

        <el-dialog
            :title="dialogLittle.title"
            :visible.sync="dialogLittle.centerDialogVisible"
            width="460px"
            center>
            <el-input class="input-dialog" maxlength="8" v-model="dialogLittle.addContent" :placeholder="dialogLittle.placeholder"></el-input>
            <p class="word-dialog-tap">*小于等于8个字符</p>

            <span slot="footer" class="dialog-footer">
                <el-button class="dialog-btn-left" @click="dialogLittle.centerDialogVisible = false">取 消</el-button>
                <el-button class="dialog-btn-right" type="primary" @click="sureAdd">增 加</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :title="dialogBig.title"
            :visible.sync="dialogBig.centerDialogVisible"
            class="resource-dialog"
            width="700px"
            center>
            <div class="dialog-big-body">
                <div class="resource-dialog-header">
                    <span>已选择{{selectUserList.length}}人</span>
                    <el-input
                        placeholder="搜索学员姓名"
                        suffix-icon="el-icon-search"
                        v-model="searchVal"
                        @keyup.enter="searchFn"
                        @blur="searchFn"
                    >
                    </el-input>
                </div>
                <div class="dialog-big-body-main" v-if="dialogBig.centerDialogVisible==true">
                    <div class="dialog-big-cont-l">
                        <div class="dialog-big-body-title">选择部门</div>
                        <div class="dialog-big-body-content" >
                            <el-tree
                                class="resource-tree"
                                :data="nameList"
                                :props="props"
                                node-key="DepartmentID"
                                ref="tree"
                                highlight-current
                                default-expand-all="true"
                                @node-click="handleNodeClick"
                            >
                            </el-tree>
                        </div>
                    </div>

                    <div class="dialog-big-cont-r">
                        <div class="el-table el-table--enable-row-transition">
                            <table class="select-table el-table__body el-table-column--selection" cellspacing="0" cellpadding="0" border="0" style="width: 100%;">
                                <thead>
                                    <tr>
                                        <th width="20%">
                                            <input type="checkbox" id="all"  v-model="all" :value="all" class="el-checkbox__original" @change="checkedAll">
                                            <label for="all" class="checkbox"></label>
                                        </th>
                                        <th width="40%">姓名</th>
                                        <th width="40%">手机号</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(item, index) in list" :key="index">
                                        <td width="20%">
                                            <input type="checkbox"  :id="'select' + item.EmployeeID " class="el-checkbox__original" :value="item.EmployeeID" v-model="curSelectId">
                                            <label :for="'select' + item.EmployeeID" class="checkbox"></label>
                                        </td>
                                        <td width="40%">{{item.Username}}</td>
                                        <td width="40%">{{item.Mobile}}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="dialog-btn-left" @click="dialogBig.centerDialogVisible = false">取 消</el-button>
                <el-button class="dialog-btn-right" type="primary" @click="getChecked">确 定</el-button>
            </span>
        </el-dialog>
    </section>
</template>

<script>

import qs from 'qs'
import editor from 'components/wangeditor.vue'
import clipImg from "components/clipImg.vue"
import com from 'js/common'
import aliyun from 'js/aliyun'

export default{
    data: function(){
        return {
            departmentList:[],
            src:"",
            uploadEndFlag:false,
            inputContent:'',
            showResCover:'',
            resTypeIDprops: {
                value: 'ResTypeID',
                label: 'ResTypeName',
                children: 'child'
            },

            all:'',
            form:{
                resName:'',
                resCateID:'',
                infoCateID:'',
                permissionType:2,
                resCover:'',
                resDesc:'',
                resAbstract:'',
                employeeIDStr:'',
                logo:'',
                resTypeID:''
            },
            curSelectId:[], //当前选择员工数据
            list:[], //员工列表数据
            selectUserList:[], //总选中员工列表
            oldcurSelectId:[], //记录以前（为当前）选中的值
            searchVal:"", //搜索可见用户
            saveSelectId:{},
            rules: {
                resName: [
                    { required: true, message: '请输入资源名称', trigger: 'blur' },
                ],
                resCateID: [
                    { required: true, message: '请选择资源分类', trigger: 'change'}
                ],
                // infoCateID: [
                //     { required: true, message: '请选择知识体系', trigger: 'change'}
                // ],
                permissionType: [
                    { required: true, message: '请选择公开范围', trigger: 'change'}
                ],
                resAbstract: [
                    { required: true, message: '请填写资源简介', trigger: 'change'}
                ],
                resCover:[
                    { required: true, message: '请上传封面', trigger: 'change'}
                ]
            },
            dialogLittle:{
                centerDialogVisible: false,
                title:'',
                placeholder:'',
                addContent:'',
                addKind:''
            },
            dialogBig:{
                centerDialogVisible: false,
                title:'',
                showSearchFlag:true
            },
            propsName: {
                label: 'DepartmentName',
                children: 'Child'
            },
            nameList:[],
            employeeIDArr:[],
            filterText: '',
            resourceKindList:[],
            // knowledgeList:[],
            comResID:this.$route.query.ComResID||'',
            tabName:this.$route.query.TabName||'',
            path: [
                {
                    'name':'资源管理',
                    'path':'/resource/book-list'
                },
                {
                    'name':'我的资源',
                    'path':'/resource/my-resource'
                },
                {
                    'name': '创建资源'
                }
            ]
        }
    },

    methods: {

        //类型树
        typeTree(firstFlag){
            axios.post('/com/res-cates/comResTypeTree', qs.stringify({
            })).then( (res) => {
                var d = res.data;
                if(d.flag == 1){
                    this.departmentList = d.data
                }else {
                    this.$message.error(d.msg)
                }
            });
        },


        getUploadImg(arr,src) {
            this.form.resCover = arr
            this.src = src
        },

        cutLength(){
            let nowContent = this.dialogLittle.addContent;
            if(nowContent.length>8){
                this.$message.error('最多输入8个字符');
                this.dialogLittle.addContent = this.dialogLittle.addContent.substring(0,8);
            }
        },

        getTabName(){       //更改面包屑路径
            let tabArr = this.resourceKindList.filter(item=>{
                return item.ResCateID==this.form.resCateID
            })
            this.tabName = tabArr[0].CateName;
        },

        gotoBackPage(){
            this.$router.push({name:'resourceMyResource',query:{TabName:this.tabName}})
        },

        submitForm(formName,uploadMaterial) {
            this.$refs[formName].validate((valid) => {
                if (valid) {

                    this.form.resTypeID = this.form.resTypeID.join(',')

                    if(this.selectUserList.length <= 0 && this.form.permissionType == '3') {
                        this.$message.error('请选择至少一个人！')
                        return false;
                    }

                    this.form.employeeIDStr = this.selectUserList.join(',')

                    if(this.comResID!=''){
                        axios.post('/com/com-res/edit', qs.stringify(this.form)).then((res) => {
                            var d = res.data;
                            if(d.flag == 1){
                                if(uploadMaterial==1){
                                    this.$router.push({name:'resourceUploadResource',query:{ComResID:d.data.ComResID,TabName:this.tabName}})
                                }else {
                                    this.$router.push({name:'resourceUploadInfo',query:{ComResID:d.data.ComResID,TabName:this.tabName}})
                                }

                            }else {
                                this.$message.error(d.msg)
                            }
                        })
                    }else {
                        axios.post('/com/com-res/add', qs.stringify(this.form)).then((res) => {
                            var d = res.data;
                            if(d.flag == 1){
                                if(uploadMaterial==1){
                                    this.$router.push({name:'resourceUploadResource',query:{ComResID:d.data.ComResID}})
                                }else {
                                    this.$router.push({name:'resourceUploadInfo',query:{ComResID:d.data.ComResID}})
                                }
                            }else {
                                this.$message.error(d.msg)
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
        },

        addResourceKind(){
            this.dialogLittle.centerDialogVisible = true;
            this.dialogLittle.title = '添加资源分类';
            this.dialogLittle.placeholder='请输入增加的资源分类名称';
            this.dialogLittle.addContent = '';
            this.dialogLittle.addKind = 1;
        },

        addKnowledge(){
            this.dialogLittle.centerDialogVisible = true;
            this.dialogLittle.title = '添加知识体系';
            this.dialogLittle.placeholder='请输入增加的知识体系名称';
            this.dialogLittle.addContent = '';
            this.dialogLittle.addKind = 2;
        },

        sureAdd(){
            if(this.dialogLittle.addKind==1){
                axios.post('/com/res-cates/add', qs.stringify({
                    cateName:this.dialogLittle.addContent
                })).then((res) => {
                    var d = res.data;
                    if(d.flag == 1){
                        this.$message.success('添加成功');
                        // this.getResourceKindList(1);
                        this.dialogLittle.centerDialogVisible = false;
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            }else {
                axios.post('/com/info-cates/add', qs.stringify({
                    cateName:this.dialogLittle.addContent
                })).then((res) => {
                    var d = res.data;
                    if(d.flag == 1){
                        this.$message.success('添加成功');
                        // this.getKnowledgeList(1);
                        this.dialogLittle.centerDialogVisible = false;
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            }
        },

        choosePeopleFirst(){
            if(this.form.permissionType==3){
                this.dialogBig.centerDialogVisible = true;
                this.dialogBig.title = '选择可见成员';
                let self = this;
                this.getEmployeeList()
                axios.post('/com/department/getDepartmentTree', qs.stringify({})).then((res) => {
                    var d = res.data;
                    if(d.flag == 1){
                        self.nameList = d.data.Row;
                        this.$refs.tree.setCheckedKeys(self.employeeIDArr);
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            }
        },

        choosePeople(){
            this.form.permissionType=3;
            this.dialogBig.centerDialogVisible = true;
            this.dialogBig.title = '选择可见成员';

            let self = this;
            this.getEmployeeList()
            axios.post('/com/department/getDepartmentTree', qs.stringify({})).then((res) => {
                var d = res.data;
                if(d.flag == 1){
                    self.nameList = d.data.Row;
                    this.$refs.tree.setCheckedKeys(self.employeeIDArr);
                }else {
                    this.$message.error(d.msg)
                }
            })
        },

        filterNode(value, data) {
            if (!value) return true;
            return data.DepartmentName.indexOf(value) != -1;
        },

        // getResourceKindList(addFlag){
        //     axios.post('/com/res-cates/list', qs.stringify({})).then((res) => {
        //         var d = res.data;
        //         if(d.flag == 1){
        //             this.resourceKindList = d.data.Row;
        //             if(addFlag==1){
        //                 this.form.resCateID = this.resourceKindList[this.resourceKindList.length-1].ResCateID
        //             }
        //         }else {
        //             this.$message.error(d.msg)
        //         }
        //     })
        // },

        getKnowledgeList(addFlag){
            axios.post('/com/info-cates/list', qs.stringify({})).then((res) => {
                var d = res.data;
                if(d.flag == 1){
                    this.knowledgeList = d.data.InfoCateList;
                    if(addFlag==1){
                        this.form.infoCateID = this.knowledgeList[this.knowledgeList.length-1].InfoCateID;
                    }
                }else {
                    this.$message.error(d.msg)
                }
            })
        },

        getEmployeeList(id) {
            let param = !!id ? {'paginate':0, 'DepartmentID' : id} : {'paginate':0}
            axios.post('/com/employee/getEmployeeList', qs.stringify(param)).then((res) => {
                var d = res.data
                if(d.flag == 1){
                    this.list = d.data.Row
                    this.parentList = this.list
                    this.checkoutUser()
                }else {
                    this.$message.error(d.msg)
                }
            })
        },

        // 全选功能
        checkedAll() {
            this.curSelectId = []
            if(!!this.all) {
                this.list.forEach((v,index)=>{
                    this.curSelectId.push(v.EmployeeID)
                })
            } else {
                this.curSelectId = []
            }

        },


        // 当前选择的部门 获取当前部门员工
        handleNodeClick(selectId){


            this.handleSelectionChange()

            this.searchVal = ''
            this.oldcurSelectId = []
            this.curSelectId = []
            this.all = false
            this.getEmployeeList(selectId.DepartmentID)

        },


        //当前选中的部门人
        handleSelectionChange() {
            // 合并数组并去重
            this.selectUserList = Array.from(new Set(this.selectUserList.concat(this.curSelectId)))

            this.selectUserList.length > 0 && this.deleteCancelUser()
        },


        // 去除当前取消的员工
        deleteCancelUser() {
            this.oldcurSelectId.forEach((v)=>{
                if(this.curSelectId.indexOf(v) == -1) {
                    this.selectUserList.splice(this.selectUserList.indexOf(v), 1)
                }
            })
        },

        //切换部门，勾选已选择的员工
        checkoutUser() {
            if(this.selectUserList.length <= 0 ) return ;

            let checkoutUserIndex = []

            this.list.forEach((v)=>{
                if(this.selectUserList.indexOf(v.EmployeeID) != -1) {
                    checkoutUserIndex.push(v.EmployeeID)
                }
            })

            this.oldcurSelectId = checkoutUserIndex
            this.curSelectId = checkoutUserIndex
        },

        getChecked(){
            this.handleSelectionChange()
            this.dialogBig.centerDialogVisible = false
        },

        searchFn() {
            if(this.searchVal == '') {
                this.list = this.parentList
            }

            this.list = this.parentList.filter((v)=>{
                return v.Username.indexOf(this.searchVal) > -1
            })
        }

    },

    mounted: function(){
        // this.getResourceKindList();
        // this.getKnowledgeList();
        this.$store.commit('setPath', this.path)

        // 资源树
        this.typeTree()

        if(this.comResID!=''){
            this.path[this.path.length-1].name = '编辑资源'

            axios.post('/com/com-res/comResDetail', qs.stringify({
                comResID: this.comResID
            })).then((res) => {
                var d = res.data;
                if(d.flag == 1){
                    let resourceInfo = d.data.ComResInfo
                    this.inputContent = resourceInfo.ResAbstract
                    // console.log(resourceInfo.ResTypeIDs.split(','))
                    this.form = {
                        comResID:this.comResID,
                        resName:resourceInfo.ResName,
                        resCateID:resourceInfo.ResCateID,
                        infoCateID:resourceInfo.InfoCateID,
                        permissionType:Number(resourceInfo.PermissionType),
                        resDesc:resourceInfo.ResDesc,
                        resAbstract:resourceInfo.ResAbstract,
                        employeeIDStr:d.data.EmployeeIDStr,
                        resCover:resourceInfo.ResCover,
                        resTypeID:String(resourceInfo.ResTypeIDs).split(',')
                    }




                    this.employeeIDArr = ( d.data.EmployeeIDStr == '' ? [] : d.data.EmployeeIDStr.split(',') )

                    this.selectUserList = this.employeeIDArr

                    axios.post('/api/system/getFullUrl', qs.stringify({
                        fileObject:JSON.stringify([{url:resourceInfo.ResCover,param:'image/resize,m_fixed,h_300,w_400'}])
                    })).then((res) => {
                        var d = res.data
                        if(d.flag == 1){
                            this.showResCover = d.data.url
                            this.src = d.data.url

                        }else {
                            this.$message.error(d.msg)
                        }
                    })

                    this.uploadEndFlag = true
                }else {
                    this.$message.error(d.msg)
                }
            })
        } else {
            if(this.$route.query.cateID == 1 || this.$route.query.cateID == 2) {
                this.form.resCateID = ""
            } else {
                //修改 在新增资源表单，资源分类默认选中上次选中的资源
                this.form.resCateID = this.$route.query.cateID
            }


            // resCateID
        }

        var self = this;
        var uploader = aliyun({
            selectfiles:'selectfiles',      //选择文件元素ID
            container:'container',          //选择元素盒子ID
            platSign:'com',                 //上传平台参数，管理后台传admin,公司管理平台com,小程序端wxapp
            fileTypeFilter:{                //过滤文件类型及大小控制
                 mime_types : [ //只允许上传图片文件
                     { title : "Image files", extensions : "jpg,gif,png,bmp,jpeg"}
                 ],
                 max_file_size : '5000kb', //最大只能上传5000kb的文件
            },
            getUploadIngFlag:function (uploadingFlag) {     //正在上传状态的回调，返回true则为正在上传中
//                self.uploadingFlag = uploadingFlag
            },
            getFileInfo:function (keyArr) {
                self.form.resCover = keyArr[0];
                axios.post('/api/system/getFullUrl', qs.stringify({
                    fileObject:JSON.stringify([{url:keyArr.join(','),param:'image/resize,m_fixed,h_300,w_400'}])
                })).then((res) => {
                    var d = res.data;
                    if(d.flag == 1){
                        self.showResCover = d.data.url;
                        self.uploadEndFlag = true;
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            }
        })

        uploader.init()
    },

    components: {
        editor,
        clipImg
    },

    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        },

        curSelectId(){

            if(this.list.length <= 0) return;

            if (this.curSelectId.length == this.list.length) {
                this.all = true
            } else {
                this.all = false
            }
        },

        selectUserList(value) {
            // console.log(value)
        }
    },
}


</script>
